﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using Web.Framework.Translate;
using System.Configuration;
using Web.PuntoDeVenta.Code;
using CrmContacto.Contracts.Config;
using System.Security.Principal;
using Web.Framework;

namespace Web.PuntoDeVenta
{
    public class Global : System.Web.HttpApplication
    {
        void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup
            string lenguajePorDefecto = ConfigurationManager.AppSettings["LenguajePorDefecto"];
            //string lenguajeFilePath = Server.MapPath(string.Format("/Localization/{0}.Crm.Bo.Localization.xml", lenguajePorDefecto));
            LocalizationHelper.ReInitialize(lenguajePorDefecto, true);
        }

        void Application_End(object sender, EventArgs e)
        {
            //  Code that runs on application shutdown

        }

        void Application_Error(object sender, EventArgs e)
        {
            // Code that runs when an unhandled error occurs
            // Response.Redirect("/ErrorForm.aspx", true);
        }

        void Session_Start(object sender, EventArgs e)
        {
            // Code that runs when a new session is started

        }

        void Session_End(object sender, EventArgs e)
        {
            // Code that runs when a session ends. 
            // Note: The Session_End event is raised only when the sessionstate mode
            // is set to InProc in the Web.config file. If session mode is set to StateServer 
            // or SQLServer, the event is not raised.
            //Response.Redirect("/Account/Login.aspx", true);
            //Server.Transfer("/Account/Login.aspx");

        }

        void Application_AcquireRequestState(object sender, EventArgs e)
        {
            // Tengo que recargar toda la información de contexto en la session si expiró.
            //// Get a reference to the current User
            IPrincipal usr = HttpContext.Current.User;
            //// If we are dealing with an authenticated forms authentication request

            if (usr.Identity.IsAuthenticated && usr.Identity.AuthenticationType == "Forms")
            {
                // Recargo si es una session nueva
                if (HttpContext.Current.Session != null && HttpContext.Current.Session.IsNewSession)
                {
                    FormsIdentity fIdent = usr.Identity as FormsIdentity;
                    string userData = fIdent.Ticket.UserData;
                    string[] userDataSplit = userData.Split('|');
                    int companyId = Convert.ToInt32(userDataSplit[0]);
                    BaseMasterPage.CompanyId = companyId;
                    BaseWebPage.CompanyId = BaseMasterPage.CompanyId;
                    int ptoVtaId = Convert.ToInt32(userDataSplit[2]);
                    string subPtoVtaIdStr = userDataSplit[3];

                    var puntosDeVenta = BasePage.GetPuntosDeVentaDto(companyId);
                    var ptoVta = puntosDeVenta.Where(p => p.Id == ptoVtaId).SingleOrDefault();
                    if (ptoVta != null)
                    {
                        if (!String.IsNullOrEmpty(subPtoVtaIdStr))
                        {
                            ptoVta.SubPuntoDeVentaIdActual = Convert.ToInt32(subPtoVtaIdStr);
                        }
                        else
                        {
                            ptoVta.SubPuntoDeVentaIdActual = null;
                        }
                    }
                    else
                    {
                        // redirigir al login
                        FormsAuthentication.RedirectToLoginPage();
                    }


                    HttpContext.Current.Session["Marca"] = Marca.GetMarca(companyId);
                    BaseMasterPage.IsAdmin = Convert.ToBoolean(userDataSplit[1]);
                    HttpContext.Current.Session["PuntoDeVentaCurrentSession"] = ptoVta;
                }
            }
        }

        void Application_OnPostAuthenticateRequest(object sender, EventArgs e)
        {
            
        }
    }
}
